package com.caiyigo.baihua.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.caiyigo.baihua.Const.UrlConfig;
import com.caiyigo.baihua.dto.Result;
import com.caiyigo.baihua.model.SystemRole;
import com.caiyigo.baihua.service.RoleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author caihaihui
 * 
 */
@Controller
@RequestMapping(value = "/system/role")
public class RoleController extends BaseController {
	@Autowired
	RoleService roleService;

	@RequestMapping(value = "/list")
	public @ResponseBody String list() throws JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.writeValueAsString(roleService.list());
	}

	@RequestMapping(value = "/tree", method = RequestMethod.POST)
	public @ResponseBody String tree(
			@RequestParam(value = "id", required = false) Integer id,
			@RequestParam(value = "passId", required = false) Integer passId)
			throws JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.writeValueAsString(roleService.getTree(id, passId));

	}

	@RequestMapping(value = "/togrant", method = RequestMethod.POST)
	public String grant(RedirectAttributes attr,
			@ModelAttribute("role") SystemRole role, String resIds) {
		Map<String, String> message = new HashMap<String, String>();
		message.put("id", role.getId() + "");
		message.put("name", role.getName());
		message.put("des", role.getDes());
		message.put("resIds", resIds);
		return RedirectAction(attr, message, UrlConfig.SYSTEM.ROLEGRANT);
	}

	@RequestMapping(value = "/grant", method = RequestMethod.POST)
	public @ResponseBody Result grant(@ModelAttribute("role") SystemRole role,
			String res_ids) {
		return roleService.batchGrant(role.getId(), res_ids);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody Result add(@ModelAttribute("role") SystemRole role) {

		return new Result(roleService.insert(role) > 0);

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody Result edit(@ModelAttribute("role") SystemRole role) {
		return roleService.edit(role);

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Result delete(
			@RequestParam(value = "id", required = false) Integer id) {
		return roleService.delete(id);
	}

}
